package com.github.rexsheng.mybatis.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;

import com.github.rexsheng.mybatis.handler.MybatisPlusColumnHandler;
import com.github.rexsheng.mybatis.handler.MybatisPlusTableHandler;
import com.github.rexsheng.mybatis.interceptor.ResultTypeInterceptor;

/**
 * @author RexSheng
 * 2021年6月8日 下午9:02:14
 * @since 1.6.0
 */

public class AutoInterceptorConfiguration {
	
	private Class<? extends IDatabaseDialect> dbType;
	
	private Class<? extends BuilderConfiguration> builderClass;
	
	private boolean mybatisPlus;
	
	public AutoInterceptorConfiguration(Class<? extends IDatabaseDialect> dbType,boolean mybatisPlus,Class<? extends BuilderConfiguration> builderClass) {
		this.dbType=dbType;
		this.mybatisPlus=mybatisPlus;
		this.builderClass=builderClass;
	}

	@Bean
	@ConditionalOnMissingBean
	public ResultTypeInterceptor resultTypeInterceptor() {
		ResultTypeInterceptor resultTypeInterceptor=new ResultTypeInterceptor();
		try {
			if(builderClass.getName().equals(BuilderConfiguration.class.getName())) {
				BuilderConfiguration config=new BuilderConfiguration();
				config.setDatabaseDialect(dbType.newInstance());
				if(mybatisPlus) {
					config.setTableHandler(new MybatisPlusTableHandler());
					config.setColumnHandler(new MybatisPlusColumnHandler());
				}
				resultTypeInterceptor.setConfig(config);
			}
			else {
				resultTypeInterceptor.setConfig(builderClass.newInstance());
			}
		}
		catch (InstantiationException | IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return resultTypeInterceptor;
	}
}
